package com.lai.hospital.interception;

import com.lai.hospital.constant.SecurityConst;
import com.lai.hospital.dto.UserInfoDTO;
import com.lai.hospital.exception.BizException;
import com.lai.hospital.service.RedisService;
import com.lai.hospital.utils.BeanCopyUtils;
import com.lai.hospital.utils.JwtTokenUtils;
import com.lai.hospital.utils.UserUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lai.hospital.constant.SecurityConst.TOKEN_FAILURE;

/**
 * @author : lai
 * @version V1.0
 * @Project: hospital-springboot
 * @Package com.lai.hospital.interception
 * @Description: jwt拦截器
 * @date Date : 2022年11月18日 22:15
 */
@Slf4j
@Component
public class JwtHandlerInterception implements HandlerInterceptor {

    @Autowired
    private RedisService redisService;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(SecurityConst.TOKEN_HEADER);//获取请求头的Authorization中的参数
        if (token == null || !token.startsWith(SecurityConst.TOKEN_PREFIX)) {//如果token为空或者不是以指定前缀开始
            SecurityContextHolder.clearContext();//清空上下文
            throw new BizException(TOKEN_FAILURE);
        }
        String tokenValue = token.replace(SecurityConst.TOKEN_PREFIX, "");
        try {
            Claims claims = jwtTokenUtils.parseJwt(tokenValue);
            return true;
        }catch (BizException e){
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
